import { z } from "zod";
import { n2DataByTransaction } from '../../../service/fund.js';
import ExcelJS from 'exceljs';

/**
 * 生成excel文件
 */
const generatorExcelFile = async data => {
    // 创建一个新的工作簿 (Workbook)
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Sheet1');

    // 添加表头
    const columns = Object.keys(data[0]).map(key => ({ header: key, key }));
    worksheet.columns = columns;

    // 添加数据行
    data.forEach(item => worksheet.addRow(item));

    // 将Excel文件保存到内存中
    const buffer = await workbook.xlsx.writeBuffer();
    return buffer;
}


export default {
    api: "exportDetails",
    name: "导出账务明细",
    description: "根据客户的要求导出支出/消费明细，比如：导出近一周的餐饮消费明细。",
    requestSchema: z.object({
        question: z.string().describe("账务明细查询的查询请求，尽可能保留客户的原话"),
    }),
    func: async ({ question }, context) => {
        const tableData = await n2DataByTransaction(question, context, 10000);
        const fileName = `${question}.xlsx`;
        const fileBuffer = await generatorExcelFile(tableData);
        context.files.push({
            name: fileName,
            buffer: fileBuffer
        });
        return `文件已经发送给客户，请在${context.terminal}查收，文件名称为 ${fileName}`;
    }
}